package com.garden.web.context.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String[] accessInputUrls = new String[]{"/", "/manager"};

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        logger.error("no authentication to access {}", request.getContextPath() + request.getRequestURI());


        //如果是ajax请求响应头会有，x-requested-with；
        if (request.getHeader("x-requested-with") != null&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
            response.getWriter().print("timeout"); //打印一个返回值，没这一行，在tabs页中无法跳出（导航栏能跳出），具体原因不明
        }
        String requestUrl = request.getRequestURI();
        String basePath = request.getContextPath();

        String forwardUrl = "";
        String tempUrl = "";
        for (String accessUrl:accessInputUrls) {
            tempUrl = basePath + accessUrl;
            if(requestUrl.startsWith(tempUrl)) {
                forwardUrl = accessUrl;
            }
        }

        return;
//        request.getRequestDispatcher(forwardUrl + "/403").forward(request, response);
    }
}
